package com.huanghuai.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class JwtUtils {

    @Value("${my.secretKey}")
    private String secret;//密钥
    public String createJwt(String userInfo ,List<String> authList){
        Date issDate = new Date();//签发1时间
       Date expireDate = new Date(issDate.getTime() + 1000*60*60*2);//过期时间 = 当前时间 + 2hour
         Map<String,Object> headerClaims = new HashMap<>();
        headerClaims.put("alg","HS256");//添加算法
        headerClaims.put("type","JWT");
        return JWT.create().withHeader(headerClaims)
                .withIssuer("thomas")//设置签发人--谁生成的jwt
                .withIssuedAt(issDate)//设置签发时间
                .withExpiresAt(expireDate)//设置过期时间
                .withClaim("user_Info",userInfo)//自定义声明
                .withClaim("userAuth",authList)//自定义声明
                .sign(Algorithm.HMAC256(secret));//使用HS256进行签名，使用secret作为密钥
    }

    public boolean verifyToken(String jwtToken){
        //创建校验器
        try {
            JWTVerifier jwtVerify = JWT.require(Algorithm.HMAC256(secret)).build();
            DecodedJWT decodedJWT = jwtVerify.verify(jwtToken);
            log.info("token验证正确");
            return true;
        } catch (Exception e) {
            log.error("token验证不正确!!!");
            return false;
        }
    }


    /**
     * 从jwt的payload里获取声明，获取用户信息
     * @param jwt
     * @return
     */
    public String getUserInfoFromToken(String jwt){
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(jwt);
            return decodedJWT.getClaim("user_Info").asString();
        } catch (IllegalArgumentException e) {
            return "";
        } catch (JWTVerificationException e) {
            return "";
        }
    }

    /**
     * 从jwt的payload里获取声明，获取的用户的权限
     * @param jwt
     * @return
     */
    public List<String> getUserAuthFromToken(String jwt){
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(jwt);
            return decodedJWT.getClaim("userAuth").asList(String.class);
        } catch (IllegalArgumentException e) {
            return null;
        } catch (JWTVerificationException e) {
            return null;
        }
    }
}
